package com.cxyd.modules.job.task.logicTask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxyd.common.utils.ApiResult;
import com.cxyd.common.utils.StringUtils;
import com.cxyd.modules.wms.dao.ContainerDao;
import com.cxyd.modules.wms.dao.UrlDao;
import com.cxyd.modules.wms.dto.PostWcsDTO;
import com.cxyd.modules.wms.entity.ContainerEntity;
import com.cxyd.modules.wms.entity.UrlEntity;
import com.cxyd.modules.wms.service.PostWcsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Component("post-wcs")
@Slf4j
public class PostWcsTask {

    private final RestTemplate restTemplate;
    private final PostWcsService postWcsService;
    private final UrlDao urlDao;
    private final ContainerDao containerDao;
    //创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    public PostWcsTask(RestTemplate restTemplate, PostWcsService postWcsService, UrlDao urlDao, ContainerDao containerDao) {
        this.restTemplate = restTemplate;
        this.postWcsService = postWcsService;
        this.urlDao = urlDao;
        this.containerDao = containerDao;
    }

    public void scanTask() {
        lock.lock();
        try {
            PostWcsDTO record = postWcsService.getOneRecord();

            if (record == null) {
                log.warn("无任务");
                return;
            }

            if (StringUtils.isBlank(record.getRequestPk()) || StringUtils.isBlank(record.getContNo())) {
                return;
            }

            //查看料箱類型
            String contNo = record.getContNo();
            String contDescription = containerDao.selectOne(new QueryWrapper<ContainerEntity>()
                    .eq("cont_no",contNo)).getContDescription();
            if(contDescription.equals("61.5*42.5*38"))
                record.setContType("2");//最高給2
            else
                record.setContType("1");


            //有任务就调用WCSurl
            String wcsUrl = urlDao.selectOne(new QueryWrapper<UrlEntity>()
                    .eq("to_system","wcs")).getToUrl();

            ApiResult respond = restTemplate.postForObject(wcsUrl, record, ApiResult.class);
            if (respond == null) {
                return;
            }
            /*发送成功则处理数据*/
            if (respond.getRequestPk().length() == 0) {
                return;
            }
            //构建map记录接收到的反馈信息
            final Map<String, Object> map = new HashMap<>();
            map.put("pk", respond.getRequestPk());
            map.put("code", respond.getCode());
            map.put("msg", respond.getMsg());
            postWcsService.updateByPk(map);

        } catch (Exception e) {
            log.error("下发搬送指令异常，causeBy:{}", e.getMessage());
        } finally {
            lock.unlock();//释放锁
        }
    }
}
